import { defineStore } from 'pinia'
import { getCartListApi } from '@/api/cart'
interface CartItem {
  id: number;
  price: number;
  count: number;
}

export const useCartStore = defineStore('cart', {
  state: () => ({
    cartList: [] as CartItem[],
  }),
  actions: {
    addCart(product: any) {
      this.cartList.push(product)
    },
    removeCart(product: any) {
      this.cartList = this.cartList.filter((item: any) => item.id !== product.id)
    },
    clearCart() {
      this.cartList = []
    },
    async getCartList() {
      const res = await getCartListApi()
      this.cartList = res.data
    },
    getCartCount() {
      return this.cartList.length
    },
    getCartTotalPrice() {
      return this.cartList.reduce((total: number, item: any) => total + item.price * item.count, 0)
    },
  },
  persist: true
})
